from osv import osv, fields
from osv.orm import intersect
    
class kdvn_contract_client(osv.osv):
    _name = "kdvn.contract.client"
    _description="KDVN Contract Client"

    def copy(self, cr, uid, id, default=None,context={}):
        raise osv.except_osv("KDVN Error","Can't Duplicate this contract")
        return super(kdvn_contract_client, self).copy(cr, uid, id, default, context)

    def _create_progress_payment(self,cr, uid, ids, context):
        a=[]
        for ctc in self.browse(cr, uid, ids, context):
            if ctc.payment_term:                
                pfc_obj=self.pool.get('kdvn.payment.from.client')
                progress_obj=self.pool.get('kdvn.progress')
                if pfc_obj.search(cr,uid, [('contract_id', '=', ctc.id)]) or progress_obj.search(cr,uid,[('contract_id','=',ctc.id)]):
                    raise osv.except_osv("Error","Payment or progress already exist !")
                else:
                    kdvn_payment_term_line_ids=self.pool.get('kdvn.payment.term.line').search(cr,uid,[('contract_id','=',ctc.id)])
                    kdvn_payments=self.pool.get('kdvn.payment.term.line').read(cr,uid,kdvn_payment_term_line_ids,['value','value_amount','sequence','name','type','id'])
                    
                    tax_per = 0.0
                    ctc_amount_e = ctc.contract_amount_e or 0.0
                    ctc_amount_m = ctc.contract_amount_m or 0.0
                    ctc_amount_vat = ctc.contract_vat or 0.0
                    if ctc_amount_e + ctc_amount_m <>0:
                        tax_per=ctc_amount_vat/(ctc_amount_e+ctc_amount_m)*100
                        
                    kdvn_payments.sort(key=lambda x:x['sequence']) #Theo ID                
                    result={}
                    result=pfc_obj._onchage_contract_id(cr,uid,ids,ctc.id)
                    if ctc.client_id:
                        result['client_id'] = ctc.client_id.id
                    else:
                        result['client_id'] = False
                        
                    if ctc.owner_id:
                        result['owner_id'] = ctc.owner_id.id
                    else:
                        result['owner_id'] = False
                        
                    if ctc.address_id:
                        result['address_id'] = ctc.address_id.id
                    else:
                        result['address_id'] = False
                    if ctc.invoice_address_id:
                        result['invoice_address_id'] = ctc.invoice_address_id.id
                    else:
                        result['invoice_address_id'] = False
                         
                    result['contract_id']=ctc.id
                    result['contract_currency_id']=ctc.contract_currency.id
                    
                    ctc_amount = ctc_amount_e + ctc_amount_m

                    adv=0.0
                    retention=0.0
                    progress_amount=0.0
                    
                    for pml in kdvn_payments:
                        if pml['type']=='adv':
                            if pml['value']=='percent':
                                adv+=ctc_amount*pml['value_amount']/100.0
                                
                        elif pml['type']=='re':
                            if pml['value']=='percent':
                                retention+=ctc_amount*pml['value_amount']/100.0

                    for pml in kdvn_payments:
                        result['adv_payment']=0.0
                        result['retention']=0.0
                        if pml['type']=='adv':
                            x_adv_payment=adv
                            result['adv_payment']=x_adv_payment
                            ctc_cal_amount_e = 0.0
                            ctc_cal_amount_m = 0.0
                            ctc_cal_amount = ctc_cal_amount_e + ctc_cal_amount_m
                        elif pml['type']=='re':
                            x_retention=retention
                            result['retention']=x_retention
                            ctc_cal_amount_e = 0.0
                            ctc_cal_amount_m = 0.0
                            ctc_cal_amount = ctc_cal_amount_e + ctc_cal_amount_m
                        else:
                            if pml['value']=='percent':
                                result['adv_payment']=-adv*pml['value_amount']/100.0
                                result['retention']=-retention*pml['value_amount']/100.0
                                ctc_cal_amount_e = ctc_amount_e*pml['value_amount']/100.0
                                ctc_cal_amount_m = ctc_amount_m*pml['value_amount']/100.0
                                ctc_cal_amount = ctc_cal_amount_e + ctc_cal_amount_m
                    
                            progress_val={}
                            progress_val['progress_no']=progress_obj._new_no(cr,uid,{'prid':ctc.id})
                            progress_val['advanced']=result['adv_payment']
                            progress_val['retention']=result['retention']
                            progress_val['amount']=ctc_cal_amount
                            progress_val['vat']=tax_per*(ctc_cal_amount)/100.0
                            progress_val['contract_id']=ctc.id
                            progress_ids=progress_obj.create(cr,uid,progress_val)

                        if not tax_per:
                            tax_amount=0.0
                        else:
                            tax_amount=ctc_cal_amount/100*tax_per
                        
                        result['taxes_percent']=int(tax_per)
                        result['kdvn_amount_tax']=tax_amount
                        
                        
                        result['amount_e']=ctc_cal_amount_e or 0.0
                        result['amount_m']=ctc_cal_amount_m or 0.0
                        
                        result['itemofrequest']=pml['name'] #ctc.description
                        
                        result['name']=ctc.description
                        result['payment_term_line_id']=pml['id']

                        result['number']=''
                        invoice_id=pfc_obj.create(cr,uid,result)

            else:
                raise osv.except_osv("Error","Please check payment term for this job !")
        return True
        
    def name_search(self, cr, user, name='', args=None, operator='ilike', context=None, limit=80):
        if not args:
            args=[]
        if not context:
            context={}
        ids = self.search(cr, user, [('contract_no','=',name)]+ args, limit=limit, context=context)
        if not len(ids):
            ids += self.search(cr, user, [('contract_no','ilike',name)]+ args, limit=limit, context=context)
        if not len(ids):
            ids += self.search(cr, user, [('description','ilike',name)]+ args, limit=limit, context=context)
        return self.name_get(cr, user, ids, context=context)
    
    def _get_quotation_lists(self, cr, uid, ids, name, arg, context=None):
        res = {}
        for id in ids:
            cr.execute('SELECT id FROM sale_order ' \
                    'WHERE contract_id =%s' % (id))
            res[id] = [x[0] for x in cr.fetchall()]
        return res
    
    def name_get(self, cr, uid, ids, context={}):
        if not len(ids):
            return []
        reads = self.read(cr, uid, ids, ['contract_no', 'description'], context)
        res = []
        for record in reads:
            name = record['description']
            if record['contract_no'] and name:
                name = record['contract_no'] + ' - ' + name
            res.append((record['id'], name))
        return res
    
    def _get_contract_currency(self,cr,uid,ids,name,args,context={}):
        res={}
        if ids:
            acc_set=",".join(map(str,ids))
            cr.execute("Select contract_id,id from project_currency where default_curr=True and contract_id in (%s)" % acc_set)
            for ctr_id,curr_id in cr.fetchall():
                res[ctr_id]=curr_id#,'contract_rate':curr_rate}
        for id in ids:
            res[id]=res.get(id,False)
        #raise osv.except_osv("E",res)
        return res
    
    def _kdvn_contract_info(self, cr, uid, ids, name, args, context={}):
        res = {}
        contract_amounte=0.0
        contract_amountm=0.0
        contract_vat=0.0
        val_temp={'contract_amount_e':0,'contract_amount_m':0,
                     'contract_vat':0,'contract_total':0,
                     'owner_id':False,'client_id':False,
                     'address_id':False,'invoice_address_id':False}
        
        address_id = False
        client_id = False
        owner_id = False
        invoice_address_id = False
        
        for x in self.browse(cr,uid,ids, context=context):
            for prj in x.project_ids:
                if not owner_id:
                    owner_id = prj.owner_id.id
                if not client_id:
                    client_id = prj.client_id.id
                if not address_id:
                    address_id = prj.address_id.id
                if not invoice_address_id:
                    invoice_address_id = prj.invoice_address_id.id
                if prj.project_type=='E':
                    contract_amounte = contract_amounte + prj.project_amount
                    contract_vat = contract_vat + prj.project_vat
                else:
                    contract_amountm = contract_amountm + prj.project_amount
                    contract_vat = contract_vat + prj.project_vat
            val={'contract_amount_e':contract_amounte,'contract_amount_m':contract_amountm,
                     'contract_vat':contract_vat,'contract_total':contract_amounte+contract_amountm+contract_vat,
                     'owner_id':owner_id,'client_id':client_id,
                     'address_id':address_id,'invoice_address_id':invoice_address_id}
            res[x.id]=val
        return res
    
    def _amount_all(self, cr, uid, ids, name, args, context=None):
        res = {}
        if ids:
            prj_ids_list = ",".join(map(str, ids))
            list_temp={'contract_amount': 0.0, 'contract_vat': 0.0,'contract_total':0.0,
                       'contract_amount_vnd':0.0,'contract_vat_vnd':0.0,'contract_total_vnd':0.0,
                       'contract_amount_usd':0.0,'contract_vat_usd':0.0,'contract_total_usd':0.0,
                       'claim_amount_vnd':0.0,'claim_vat_vnd':0.0,'claim_total_vnd':0.0,
                       'claim_amount_balance_vnd':0.0,'claim_vat_balance_vnd':0.0,'claim_total_balance_vnd':0.0,
                       'claim_amount_usd':0.0,'claim_vat_usd':0.0,'claim_total_usd':0.0,
                       'claim_amount_balance_usd':0.0,'claim_vat_balance_usd':0.0,'claim_total_balance_usd':0.0,
                       'received_usd':0.0,'received_vat_usd':0.0,'received_total_usd':0.0,
                       'received_amount_balance_usd':0.0,'received_vat_balance_usd':0.0,'received_total_balance_usd':0.0,
                       'received_vnd':0.0,'received_vat_vnd':0.0,'received_total_vnd':0.0,
                       'received_amount_balance_vnd':0.0,'received_vat_balance_vnd':0.0,'received_total_balance_vnd':0.0
                       }            
            for id in ids:
                res[id]=list_temp
            cr.execute("Select \
                            vwtemp.id,\
                            contract_amount,\
                            contract_vat,\
                            contract_amount+contract_vat as contract_total,\
                            \
                            contract_amount_usd,\
                            contract_vat_usd,\
                            contract_amount_usd + contract_vat_usd as contract_total_usd,\
                            \
                            received_rate,\
                            \
                            contract_amount_vnd,\
                            contract_vat_vnd,\
                            contract_amount_vnd + contract_vat_vnd as contract_total_vnd,\
                            \
                            claim_amount_usd,\
                            claim_tax_usd as claim_vat_usd,\
                            claim_amount_usd+claim_tax_usd as claim_total_usd,\
                            \
                            claim_amount_vnd as claim_amount_vnd,\
                            claim_tax_vnd as claim_vat_vnd,\
                            claim_amount_vnd+claim_tax_vnd as claim_total_vnd,\
                            \
                            received_usd,\
                            received_tax_usd as received_vat_usd,\
                            received_usd+received_tax_usd as received_total_usd,\
                            \
                            received_vnd,\
                            received_tax_vnd as received_vat_vnd,\
                            received_vnd+received_tax_vnd as received_total_vnd\
                        from \
                            (Select\
                                id,\
                                sum(contract_amount) as contract_amount,\
                                sum(contract_vat) as contract_vat,\
                                \
                                sum(contract_amount_usd) as contract_amount_usd,\
                                sum(contract_vat_usd) as contract_vat_usd,\
                                \
                                sum(contract_amount_vnd) as contract_amount_vnd,\
                                sum(contract_vat_vnd) as contract_vat_vnd,\
                                \
                                sum(claim_amount_vnd) as claim_amount_vnd,\
                                sum(claim_tax_vnd) as claim_tax_vnd,\
                                sum(claim_amount_usd) as claim_amount_usd,\
                                sum(claim_tax_usd) as claim_tax_usd,\
                                sum(received_usd) as received_usd,\
                                sum(received_tax_usd) as received_tax_usd,\
                                sum(received_vnd) as received_vnd,\
                                sum(received_tax_vnd) as received_tax_vnd,\
                                case when sum(plan_cost_vnd+plan_vat_vnd) is null or sum(plan_cost_vnd+plan_vat_vnd)=0 then 1 else\
                                sum(contract_amount_vnd + contract_vat_vnd)/sum(plan_cost_vnd+plan_vat_vnd) end as received_rate\
                            from vwproject_contract_received_summary \
                            group by id) vwtemp\
                            where vwtemp.id in (%s)" % (prj_ids_list))
        for prj_list in cr.dictfetchall():
            tmp_id=prj_list.pop('id')
            received_rate=prj_list.pop('received_rate')
            res[tmp_id]=prj_list
            #res[tmp_id].update(bg_lists.get(tmp_id,bg_temp))
            
            res[tmp_id]['claim_amount_balance_vnd'] = res[tmp_id]['claim_amount_vnd'] - res[tmp_id]['received_vnd'] #res[tmp_id]['contract_amount_vnd']-
            res[tmp_id]['claim_vat_balance_vnd'] = res[tmp_id]['claim_vat_vnd'] - res[tmp_id]['received_vat_vnd'] # res[tmp_id]['contract_vat_vnd']-
            res[tmp_id]['claim_total_balance_vnd'] = res[tmp_id]['claim_total_vnd'] - res[tmp_id]['claim_total_usd'] # res[tmp_id]['contract_total_vnd']-
            
            res[tmp_id]['claim_amount_balance_usd'] =res[tmp_id]['claim_amount_usd'] - res[tmp_id]['received_usd'] #  res[tmp_id]['contract_amount_usd']-
            res[tmp_id]['claim_vat_balance_usd'] = res[tmp_id]['claim_vat_usd'] - res[tmp_id]['received_vat_usd']#res[tmp_id]['contract_vat_usd']-
            res[tmp_id]['claim_total_balance_usd'] = res[tmp_id]['claim_total_usd'] - res[tmp_id]['received_total_usd']#res[tmp_id]['contract_total_usd']-
            
            res[tmp_id]['received_amount_balance_vnd'] = res[tmp_id]['contract_amount_vnd']-res[tmp_id]['received_vnd']
            res[tmp_id]['received_vat_balance_vnd'] = res[tmp_id]['contract_vat_vnd']-res[tmp_id]['received_vat_vnd']
            res[tmp_id]['received_total_balance_vnd'] = res[tmp_id]['contract_total_vnd']-res[tmp_id]['received_total_vnd']
            
            res[tmp_id]['received_amount_balance_usd'] = res[tmp_id]['contract_amount_usd']-res[tmp_id]['received_usd']
            res[tmp_id]['received_vat_balance_usd'] = res[tmp_id]['contract_vat_usd']-res[tmp_id]['received_vat_usd']
            res[tmp_id]['received_total_balance_usd'] = res[tmp_id]['contract_total_usd']-res[tmp_id]['received_total_usd']
 
        return res
        
    def _get_quotation_info(self, cr, uid, ids, name, args, context=None):
        #tmp={'quotations':False, 'scopeofwork':False}
        res={}
        if ids:
            for id in ids:
                
                cr.execute("Select \
                                name,\
                                trim(description)\
                            from \
                                sale_order so \
                            where\
                                contract_id=%s \
                                and state='done' order by name" % (id))
                quotations=False
                #scopeofwork=False
                for qno,scope in cr.fetchall():
                    if quotations:
                        if qno:
                            quotations=quotations+"; "+qno
                    else:
                        quotations=qno
#                    if scopeofwork:
#                        if scope:
#                            scopeofwork = scopeofwork + "; " +scope 
#                    else:
#                        scopeofwork = scope
                res[id]=quotations#, 'scopeofwork': scopeofwork}
        return res
    
    def _newcode_suggest(self,cr,uid,context={}):
        selection=[]
        cr.execute("Select newcode,newcode || ': ' || name  from vwnewcode_contract order by newcode asc")
        list_newcode=cr.fetchall()
        return list_newcode

    def _get_payment_term(self, cr, uid, ids, name, args, context=None):
        res={}
        if ids:
            for id in ids:
                res[id] = False
            order_ids = ','.join(map(str,ids))
            cr.execute("Select \
                            kcc.id,\
                            ltrim(rtrim(to_char(value_amount,'990" +chr(37)+ "'))) || ' ' || pt.name as name \
                        from \
                            kdvn_contract_client kcc \
                        left join\
                            kdvn_payment_term_line pt on kcc.id=contract_id where kcc.id in (%s) and pt.id>0 order by kcc.id,pt.sequence" % (order_ids))
            count = 0
            list_number = {1:'st',2:'nd',3:'rd',11:'th',12:'th',13:'th'}
            tmp_obj = cr.fetchall()
            if len(tmp_obj)<=1:
                for po_id,term_name in tmp_obj:
                    res[po_id] = term_name
            else:
                for po_id,term_name in tmp_obj:
                    count+=1
                    count_str=str(count)
                    end_char = count%10
                    if count>10 and count<=13:
                        tt = list_number[count]
                    elif end_char in list_number:
                        tt =  list_number[end_char]
                    else:
                        tt = 'th'
                        
                    if res[po_id]:
                        res[po_id] = res[po_id] + "\n" + count_str + tt + ": " + term_name
                    else:
                        res[po_id] = count_str + tt + ": " + term_name
        #raise osv.except_osv('E',res)
        return res
    
#    def write(self, cr, uid, ids, vals, context=None):
#        osv.osv.write(self, cr, uid, ids,vals,context=context)
#        #raise osv.except_osv('e',vals)
#        return True
           
    _columns={
                'contract_no':fields.char('Number',size=50,required=True),
                'newcode_suggest':fields.selection(_newcode_suggest,'New Code',size=128,store=False),
                
                'combine_term':fields.function(_get_payment_term,method=True,type='text',string='Combine Term Name'),
                
                'date':fields.date('Date of contract',select=2),
                'registration_date':fields.date("Reg. Date",select=2),
                'started_date':fields.date('Started Date',select=2),
                'completion_date':fields.date('Completion Date',select=2),
                'closed_date':fields.date('Closed Date',select=2),
                'contract_ref':fields.char('Contract Ref.',size=100),
                'project_name':fields.char('Prj. Name',size=255),
                'description':fields.char('Description',size=100,required=True),
                'progressno':fields.integer('Progress No'), #Temp for store                 
                'contract_rate':fields.float("Ex.Rate",readonly=True,digits=(16,2)),
                'quotations':fields.function(_get_quotation_info,type='char',
                                             size='128',method=True,string='Quotations'),#,multi='_quo_info'
                #'scopeofwork':fields.function(_get_quotation_info,type='char',
                 #                            size='128',method=True,string='Scope Of Work',multi='_quo_info'),                                             
                
                ## Relation Fields
                #'project_ids':fields.one2many('kdvn.project','contract_id','Project'),
                'contract_currency_ids':fields.one2many('project.currency','contract_id','Project Currencies'),
                'payment_term':fields.one2many('kdvn.payment.term.line','contract_id','Payment Term'),
                'progress_line': fields.one2many('kdvn.progress','contract_id',"Progress"),
                'payment_ids':fields.one2many("kdvn.payment.from.client",'contract_id','Payment',readonly=True),
                'quotation_ids':fields.function(_get_quotation_lists,relation='sale.order',type='one2many',string='Quotations',method=True),
                #'quotation_ids':fields.one2many('sale.order','contract_id','Quotations'),
                
                'owner_id':fields.many2one('res.partner','Owner'),
                'client_id':fields.many2one('res.partner','Client'),
                'address_id':fields.many2one('res.partner.address','Address'),
                'invoice_address_id':fields.many2one('res.partner.address','Invoice Address'),
                
                'contract_currency':fields.function(_get_contract_currency,
                                                    type='many2one',
                                                    relation="project.currency",
                                                    string="Cur.",
                                                    readonly=True,
                                                    method=True,
                                                    store=True,
                                                    help='Use below Currency System to update'),
                'contract_amount_e':fields.float('Contract Amt. E.',digits=(16,2),readonly=True),
                'contract_amount_m':fields.float('Contract Amt. M.',digits=(16,2),readonly=True),
                'contract_vat':fields.float('Contract V.A.T.',digits=(16,2),readonly=True),
                'contract_total':fields.float('Contract Total',digits=(16,2),readonly=True),
                'contract_total_manual':fields.float('Contract Total',digits=(16,2)),
                
                'attached_contract_sent':fields.boolean('Contract Sent'),
                'attached_contract_received':fields.boolean('Contract Received'),
                'attached_approved_quotation':fields.boolean("Approved Quotation"),
                #'attached_progress_sent':fields.boolean('Progress Sent'),
                #'attached_progress_received':fields.boolean('Progress Received'),
               
                ## Contract Amount ##
                #'contract_amount':fields.function(_amount_all,method=True,type='float',string='Contract Amount (Contract Currency)',multi='get_contract_info'),
                #'contract_vat':fields.function(_amount_all,method=True,type='float',string='Contract VAT (Contract Currency)',multi='get_contract_info'),
                #'contract_total':fields.function(_amount_all,method=True,type='float',string='Contract Total (Contract Currency)',multi='get_contract_info'),
                
                ## Contract Amount VND ##
                'contract_amount_vnd':fields.function(_amount_all,method=True,type='float',string='Contract Amount in VND',multi='get_contract_info'),
                'contract_vat_vnd':fields.function(_amount_all,method=True,type='float',string='Contract VAT in VND',multi='get_contract_info'),
                'contract_total_vnd':fields.function(_amount_all,method=True,type='float',string='Contract Total in VND',multi='get_contract_info'),
                
                ## Contract Amount USD ##
                'contract_amount_usd':fields.function(_amount_all,method=True,type='float',string='Contract Amount in USD',multi='get_contract_info'),
                'contract_vat_usd':fields.function(_amount_all,method=True,type='float',string='Contract Amount in USD',multi='get_contract_info'),
                'contract_total_usd':fields.function(_amount_all,method=True,type='float',string='Contract Amount in USD',multi='get_contract_info'),
                
                ## Total Budget in VND & USD ##
#                'total_budget_vnd':fields.function(_amount_all,method=True,type='float',string='Total Budget Amount in VND',multi='get_contract_info'),
#                'total_budget_usd':fields.function(_amount_all,method=True,type='float',string='Total Budget Amount in USD',multi='get_contract_info'),
                
                ## Expense Detail
#                'expense_vnd':fields.function(_amount_all,method=True,type='float',string='Expense VND',multi='get_contract_info'),
#                'expense_usd':fields.function(_amount_all,method=True,type='float',string='Expense USD',multi='get_contract_info'),
#                'payment_vnd':fields.function(_amount_all,method=True,type='float',string='Paid VND',multi='get_contract_info'),
#                'payment_usd':fields.function(_amount_all,method=True,type='float',string='Paid USD',multi='get_contract_info'),
                
                ## Contract balance USD & VND ##
                #'contract_balance_vnd':fields.function(_amount_all,method=True,type='float',string='Contract Budget Balance in VND',multi='get_contract_info'),
                #'contract_balance_usd':fields.function(_amount_all,method=True,type='float',string='Contract Budget Balance in USD',multi='get_contract_info'),
                
                ## Claim & Contract and Claim Balance in VND ##
                'claim_amount_vnd':fields.function(_amount_all,method=True,type='float',string='Claim Amount in VND',multi='get_contract_info'),
                'claim_vat_vnd':fields.function(_amount_all,method=True,type='float',string='Claim VAT in VND',multi='get_contract_info'),
                'claim_total_vnd':fields.function(_amount_all,method=True,type='float',string='Claim Total in VND',multi='get_contract_info'),
                
                'claim_amount_balance_vnd':fields.function(_amount_all,method=True,type='float',string='Claim Amount Balance in VND',multi='get_contract_info'),
                'claim_vat_balance_vnd':fields.function(_amount_all,method=True,type='float',string='Claim VAT Balance in VND',multi='get_contract_info'),
                'claim_total_balance_vnd':fields.function(_amount_all,method=True,type='float',string='Claim Total Balance in VND',multi='get_contract_info'),
                
                ## Claim & Contract and Claim Balance in USD ##
                'claim_amount_usd':fields.function(_amount_all,method=True,type='float',string='Claim Amount in USD',multi='get_contract_info'),
                'claim_vat_usd':fields.function(_amount_all,method=True,type='float',string='Claim VAT in in USD',multi='get_contract_info'),
                'claim_total_usd':fields.function(_amount_all,method=True,type='float',string='Claim Total in USD',multi='get_contract_info'),
                
                'claim_amount_balance_usd':fields.function(_amount_all,method=True,type='float',string='Claim Amount Balance in USD',multi='get_contract_info'),
                'claim_vat_balance_usd':fields.function(_amount_all,method=True,type='float',string='Claim VAT Balance in USD',multi='get_contract_info'),
                'claim_total_balance_usd':fields.function(_amount_all,method=True,type='float',string='Claim Total Balance in USD',multi='get_contract_info'),
                
                ## Received & Balance VND ##
                
                'received_vnd':fields.function(_amount_all,method=True,type='float',string='Received Amount in VND',multi='get_contract_info'),
                'received_vat_vnd':fields.function(_amount_all,method=True,type='float',string='Received vat in VND',multi='get_contract_info'),
                'received_total_vnd':fields.function(_amount_all,method=True,type='float',string='Received Total in VND',multi='get_contract_info'),
                
                'received_amount_balance_vnd':fields.function(_amount_all,method=True,type='float',string='Received Balance in VND',multi='get_contract_info'),
                'received_vat_balance_vnd':fields.function(_amount_all,method=True,type='float',string='Received Balance in VND',multi='get_contract_info'),
                'received_total_balance_vnd':fields.function(_amount_all,method=True,type='float',string='Received Balance in VND',multi='get_contract_info'),
                
                ## Received & Balance USD ##
                'received_usd':fields.function(_amount_all,method=True,type='float',string='Received Amount in USD',multi='get_contract_info'),
                'received_vat_usd':fields.function(_amount_all,method=True,type='float',string='Received vat in USD',multi='get_contract_info'),
                'received_total_usd':fields.function(_amount_all,method=True,type='float',string='Received Total in USD',multi='get_contract_info'),
                
                'received_amount_balance_usd':fields.function(_amount_all,method=True,type='float',string='Received Balance in USD',multi='get_contract_info'),
                'received_vat_balance_usd':fields.function(_amount_all,method=True,type='float',string='Received Balance in USD',multi='get_contract_info'),
                'received_total_balance_usd':fields.function(_amount_all,method=True,type='float',string='Received Balance in USD',multi='get_contract_info')                
                }
    _sql_constraints = [('kdvn_unique_contract_no', 'unique(contract_no)', 'KDVN Error: The contract number must be unique!')]
    #On change for view area
    def _onchange_client_id(self, cr, uid, ids, partner_id):
        invoice_addr_id = False
        address_id = False
        if partner_id:
            res = self.pool.get('res.partner').address_get(cr, uid, [partner_id], ['default', 'invoice'])
            invoice_addr_id = res['invoice']
            address_id = False
            if res['default']:
                address_id = res['default'] 
            if not invoice_addr_id and address_id:  
                invoice_addr_id =address_id
                
        result = {'value': {'invoice_address_id': invoice_addr_id,
                            'address_id':address_id}}
        return result
    
    def _onchange_suggest_code(self, cr, uid, ids,new_code):
        if new_code:
            val={'value':{'contract_no':new_code,'newcode_suggest':False}}
        else:
            val={}
        return val
    
    #Trigger when create new Contract
    def create(self, cr, uid, vals, context={}):        
        id_test=osv.osv.create(self, cr, uid, vals, context=context)
        
        kdvn_payment_term_line_obj=self.pool.get('kdvn.payment.term.line')         
        kdvn_payment_line_id=kdvn_payment_term_line_obj.create(cr,uid,{'value_amount':100.0,'name':'Payment',
                                                 'sequence':1,'contract_id':id_test})
        new_id=self.pool.get('project.currency')._create_currency(cr,uid,id_test,'contract',context)
        return id_test    
kdvn_contract_client()